from sqlalchemy.orm import backref
from datetime import datetime
from exts import db

# 用户表
class UserModel(db.Model):
    __tablename__ = "user"
    uid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(300), nullable=False)

class ProductModel(db.Model):
    __tablename__ = "products"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(63))
    barcode = db.Column(db.String(30))
    price = db.Column(db.Numeric(10, 2))
    stock_quantity = db.Column(db.Integer, nullable=False)
    supplier = db.Column(db.String(30))


class PurchaseOrderModel(db.Model):
    __tablename__ = "purchase_orders"
    id = db.Column(db.Integer, primary_key=True)
    purchase_time = db.Column(db.DateTime, nullable=False)


class ProductPurchaseOrderModel(db.Model):
    __tablename__ = "product_purchase_order_relationship"
    id = db.Column(db.Integer, primary_key=True)
    purchase_orders_id= db.Column(db.Integer, db.ForeignKey('purchase_orders.id'))
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=False)
    purchase_quantity = db.Column(db.Integer, nullable=False)
    purchase_price = db.Column(db.Numeric(10, 2))
    total_amount = db.Column(db.Numeric(10, 2))

    purchase_orders = db.relationship(PurchaseOrderModel, backref='product_purchase_order_relationship',cascade="all,delete")
    product = db.relationship(ProductModel, backref='product_purchase_order_relationship')

class SalesOrderModel(db.Model):
   __tablename__ = "sales_orders"
   id = db.Column(db.Integer,primary_key=True,nullable=False)
   sales_time = db.Column(db.DateTime)
   member_id = db.Column(db.Integer, db.ForeignKey('members.id'),nullable=False)
   status = db.Column(db.Boolean, default=False)
   total_amount = db.Column(db.Numeric(10, 2))

   member = db.relationship('MemberModel', backref='sales_orders')

class ProductSalesOrderModel(db.Model):
    __tablename__ = "product_sales_orders"
    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=False)
    salesorder_id=db.Column(db.Integer, db.ForeignKey('sales_orders.id',ondelete='CASCADE'), nullable=False)
    sales_quantity = db.Column(db.Integer)
    amount = db.Column(db.Numeric(10, 2))

    product = db.relationship('ProductModel', backref='product_sales_orders')

class MemberModel(db.Model):
    __tablename__ = "members"
    id = db.Column(db.Integer, primary_key=True)
    points = db.Column(db.Integer)
    mobile = db.Column(db.String(50),unique=True)
    name = db.Column(db.String(50))

